package com.h5ve.data.listener;

import com.alibaba.druid.pool.DruidDataSource;
import com.h5ve.data.entity.Datasource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.anyline.data.datasource.DataSourceHolder;
import org.anyline.entity.EntitySet;
import org.anyline.proxy.ServiceProxy;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RefreshedEventListener {

    @SneakyThrows
    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationEvent(ContextRefreshedEvent event) {
        EntitySet<Datasource> datasources = ServiceProxy.service().selects(Datasource.class, "status=0");
        for (Datasource datasource : datasources.getDatas()) {
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(datasource.getDriverClassName());
            ds.setUrl(datasource.getUrl());
            ds.setUsername(datasource.getUsername());
            ds.setPassword(datasource.getPassword());
            DataSourceHolder.reg(datasource.getAlias(), ds);
            log.error("reg: " + datasource.getAlias());
        }
    }
}
